<template>
  <div class="page-layout">
    <div class="header-container">
      <el-form :inline="true" :model="searchForm" class="header-form search-form">
        <el-form-item label="开始时间" class="time-period-picker">
          <el-date-picker v-model="searchForm.startDate" type="date" placeholder="开始时间" value-format="YYYY-MM-DD" :clearable="false" />
        </el-form-item>
        <el-form-item label="结束时间" class="time-period-picker">
          <el-date-picker v-model="searchForm.endDate" type="date" placeholder="结束时间" value-format="YYYY-MM-DD" :clearable="false" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table-container">
      <el-table
        :data="tableData"
        height="70vh"
        :header-cell-style="{ textAlign: 'center' }"
        :cell-style="{ textAlign: 'center', padding: '4px 8px', height: 'auto' }"
        :span-method="spanMethod"
        border
      >
        <el-table-column prop="shijian" label="" width="120" />
        <el-table-column prop="type" label="" width="100" />
        <!-- 24小时列 -->
        <el-table-column :prop="`h${i - 1}`" :label="`${i - 1}点至${i}点`" v-for="i in 24" width="240">
          <template #default="scope">
            <template v-if="scope.row.type === '实际原因'">
              <template v-if="editStatus[getEditKey(scope.row, scope.column.property)]">
                <textarea
                  v-model="scope.row[scope.column.property as keyof TableRow]"
                  class="cell-textarea"
                  @input="autoResize($event.target as HTMLTextAreaElement)"
                  @mounted="autoResize($event.target as HTMLTextAreaElement)"
                ></textarea>
                <div class="cell-buttons">
                  <el-button @click="handleCellSave(scope.row, scope.column.property)" type="text" size="mini" icon="Check" color="green">
                    <el-icon><Check /></el-icon>
                  </el-button>
                  <el-button @click="handleCellCancel(scope.row, scope.column.property)" type="text" size="mini" icon="Close" color="gray">
                    <el-icon><Close /></el-icon>
                  </el-button>
                </div>
              </template>
              <template v-else>
                {{ scope.row[scope.column.property] ?? '' }}
                <el-button @click="handleCellEdit(scope.row, scope.column.property)" type="text" size="mini" icon="Edit" color="primary">
                  <el-icon><Edit /></el-icon>
                </el-button>
              </template>
            </template>
            <template v-else>
              {{ scope.row[scope.column.property] ?? '' }}
            </template>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, nextTick } from 'vue';
  import { Edit, Check, Close } from '@element-plus/icons-vue';
  import { ElMessage } from 'element-plus';
  import dayjs from 'dayjs';
  import { tcm2280Api } from '/@/api/report/TCM2208MillUnit/index';
  import { error } from 'jquery';

  // 1. 定义明确类型，替代 any（提升类型安全）
  interface TableRow {
    shijian: string;
    type: string;
    h0: string | number | null;
    h1: string | number | null;
    h2: string | number | null;
    h3: string | number | null;
    h4: string | number | null;
    h5: string | number | null;
    h6: string | number | null;
    h7: string | number | null;
    h8: string | number | null;
    h9: string | number | null;
    h10: string | number | null;
    h11: string | number | null;
    h12: string | number | null;
    h13: string | number | null;
    h14: string | number | null;
    h15: string | number | null;
    h16: string | number | null;
    h17: string | number | null;
    h18: string | number | null;
    h19: string | number | null;
    h20: string | number | null;
    h21: string | number | null;
    h22: string | number | null;
    h23: string | number | null;
  }

  interface SearchForm {
    startDate: string;
    endDate: string;
  }

  // 2. 响应式数据（类型明确）
  const searchForm = reactive<SearchForm>({
    startDate: '',
    endDate: '',
  });

  const tableData = ref<TableRow[]>([
    {
      shijian: '20251124',
      type: '计划产量',
      h0: '374.460',
      h1: '330.320',
      h2: '265.180',
      h3: '241.450',
      h4: '202.553',
      h5: '270.378',
      h6: '249.050',
      h7: '277.497',
      h8: '252.333',
      h9: '256.740',
      h10: '325.539',
      h11: '348.600',
      h12: '360.411',
      h13: '369.149',
      h14: '308.326',
      h15: '280.284',
      h16: '300.620',
      h17: '253.849',
      h18: '177.962',
      h19: '211.110',
      h20: '209.442',
      h21: '374.432',
      h22: '264.723',
      h23: '269.682',
    },
    {
      shijian: '20251124',
      type: '实际产量',
      h0: '217.880',
      h1: '443.180',
      h2: '371.750',
      h3: '343.720',
      h4: '220.710',
      h5: '213.200',
      h6: '304.070',
      h7: '297.280',
      h8: '250.030',
      h9: '183.230',
      h10: '185.350',
      h11: '435.030',
      h12: '465.680',
      h13: '287.390',
      h14: '274.940',
      h15: '234.720',
      h16: '294.010',
      h17: '295.170',
      h18: '274.870',
      h19: '146.660',
      h20: '253.930',
      h21: '309.850',
      h22: '301.153',
      h23: '314.690',
    },
    {
      shijian: '20251124',
      type: '计划卷数',
      h0: '12',
      h1: '11',
      h2: '10',
      h3: '9',
      h4: '9',
      h5: '13',
      h6: '12',
      h7: '12',
      h8: '12',
      h9: '13',
      h10: '12',
      h11: '10',
      h12: '12',
      h13: '14',
      h14: '12',
      h15: '12',
      h16: '15',
      h17: '11',
      h18: '9',
      h19: '12',
      h20: '11',
      h21: '11',
      h22: '10',
      h23: '12',
    },
    {
      shijian: '20251124',
      type: '实际卷数',
      h0: '7',
      h1: '15',
      h2: '14',
      h3: '13',
      h4: '10',
      h5: '11',
      h6: '15',
      h7: '13',
      h8: '12',
      h9: '9',
      h10: '8',
      h11: '13',
      h12: '16',
      h13: '11',
      h14: '11',
      h15: '11',
      h16: '15',
      h17: '13',
      h18: '14',
      h19: '9',
      h20: '13',
      h21: '9',
      h22: '11',
      h23: '13',
    },
    {
      shijian: '20251124',
      type: '未达标理论原因',
      h0: '重焊卷数：1，最高重焊5次;重焊速度未达标数：2;',
      h1: null,
      h2: null,
      h3: null,
      h4: null,
      h5: '重焊卷数：3，最高重焊1次;重焊速度未达标数：3;',
      h6: null,
      h7: null,
      h8: null,
      h9: '重焊卷数：2，最高重焊2次;重焊速度未达标数：1;',
      h10: '重焊卷数：3，最高重焊4次;重焊速度未达标数：4;',
      h11: null,
      h12: null,
      h13: '重焊卷数：4，最高重焊5次;重焊速度未达标数：6;',
      h14: '重焊速度未达标数：4;',
      h15: '重焊卷数：2，最高重焊2次;',
      h16: null,
      h17: null,
      h18: null,
      h19: '重焊卷数：2，最高重焊3次;重焊速度未达标数：8;',
      h20: null,
      h21: '重焊卷数：1，最高重焊1次;重焊速度未达标数：2;',
      h22: null,
      h23: null,
    },
    {
      shijian: '20251124',
      type: '实际原因',
      h0: null,
      h1: null,
      h2: null,
      h3: null,
      h4: null,
      h5: null,
      h6: null,
      h7: null,
      h8: null,
      h9: null,
      h10: null,
      h11: null,
      h12: null,
      h13: null,
      h14: null,
      h15: null,
      h16: null,
      h17: null,
      h18: null,
      h19: null,
      h20: null,
      h21: null,
      h22: null,
      h23: null,
    },
  ]);

  const cellOriginalValue = reactive<Record<string, string>>({});

  const handleCellEdit = (row: TableRow, columnProperty: string) => {
    const key = getEditKey(row, columnProperty);
    cellOriginalValue[key] = row[columnProperty as keyof TableRow]?.toString() ?? '';
    editStatus[key] = true;
    nextTick(() => {
      const textarea = document.querySelector<HTMLTextAreaElement>(`.cell-textarea[data-key="${key}"]`);
      textarea && autoResize(textarea);
    });
  };

  const handleCellSave = async (row: TableRow, columnProperty: string) => {
    const key = getEditKey(row, columnProperty);
    try {
      const param = {
        shijian: row.shijian,
        hour: columnProperty.match(/\d+/)?.[0],
        reason: row[columnProperty as keyof TableRow],
      };
      const result = await tcm2280Api.updateReason(param);
      if (result.data.status != 2000) {
        throw error;
      }
      ElMessage.success(`保存成功`);
    } catch (err: any) {
      row[columnProperty as keyof TableRow] = '';
      console.error('保存失败' + err.message + err);
      ElMessage.error('保存失败');
    }
    editStatus[key] = false;
  };

  const handleCellCancel = (row: TableRow, columnProperty: string) => {
    const key = getEditKey(row, columnProperty);
    const originalValue = cellOriginalValue[key];
    row[columnProperty as keyof TableRow] = originalValue ?? '';
    delete cellOriginalValue[key];
    // 退出编辑状态
    editStatus[key] = false;
    ElMessage.info('已取消编辑，还原原始内容');
  };

  const getEditKey = (row: TableRow, columnProperty: string) => {
    return `${row.shijian}-${row.type}-${columnProperty}`;
  };

  const initEditStatus = (): Record<string, boolean> => {
    const status: Record<string, boolean> = {};
    const hourColumns = Array.from({ length: 24 }, (_, i) => `h${i}`); // ['h0', 'h1', ..., 'h23']

    tableData.value.forEach((row) => {
      if (row.type === '实际原因') {
        // 仅实际原因行需要编辑状态
        hourColumns.forEach((col) => {
          const key = getEditKey(row, col);
          status[key] = false; // 初始均为非编辑状态
        });
      }
    });
    return status;
  };

  const editStatus = reactive<Record<string, boolean>>(initEditStatus());

  const autoResize = (textarea: HTMLTextAreaElement | null | undefined) => {
    // 安全检查：排除 null/undefined/非 textarea 元素
    if (!textarea || !(textarea instanceof HTMLTextAreaElement)) return;

    textarea.style.height = 'auto';
    const newHeight = Math.min(Math.max(textarea.scrollHeight + 10, 40), 300);
    textarea.style.height = `${newHeight}px`;
  };

  const handleSearch = async () => {
    if (!searchForm.startDate || !searchForm.endDate || searchForm.startDate > searchForm.endDate) {
      ElMessage.error('请选择有效的日期范围');
      return;
    }
    fetchData();
  };

  const handleReset = async () => {
    searchForm.startDate = dayjs().subtract(1, 'day').format('YYYY-MM-DD');
    searchForm.endDate = dayjs().subtract(1, 'day').format('YYYY-MM-DD');
    fetchData();
  };

  const spanMethod = ({ row, rowIndex, columnIndex }: { row: TableRow; rowIndex: number; columnIndex: number }) => {
    if (columnIndex === 0) {
      // 按 shijian 合并（可根据实际需求调整合并条件）
      if (rowIndex === 0 || row.shijian !== tableData.value[rowIndex - 1]?.shijian) {
        let rowspan = 1;
        while (rowIndex + rowspan < tableData.value.length && tableData.value[rowIndex + rowspan].shijian === row.shijian) {
          rowspan++;
        }
        return { rowspan, colspan: 1 };
      } else {
        return { rowspan: 0, colspan: 0 };
      }
    }
    return { rowspan: 1, colspan: 1 };
  };

  const fetchData = async () => {
    try {
      const param = {
        beginDate: searchForm.startDate,
        endDate: searchForm.endDate,
      };
      const result = await tcm2280Api.getHourData(param);
      if (result.data.status != 2000) {
        throw error;
      }
      tableData.value = result.data.data;
    } catch (err: any) {
      tableData.value = [];
      console.error('获取小时产量数据失败' + err.message + err);
      ElMessage.error('获取小时产量数据失败');
    }
  };

  onMounted(() => {
    searchForm.startDate = dayjs().subtract(1, 'day').format('YYYY-MM-DD');
    searchForm.endDate = dayjs().subtract(1, 'day').format('YYYY-MM-DD');
    fetchData();
  });
</script>
<style lang="less" scoped>
  .page-layout {
    display: flex;
    flex-direction: column;
    background-color: #fff;
    min-height: 90vh;
    gap: 1vh;
    padding: 20px;
    width: 99.5%;
  }

  .header-container {
    min-height: 6vh;
    width: 100%;
  }

  .table-container {
    padding: 12px;
    border-radius: 8px;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
    overflow: hidden;
    border: 1px solid #ccc;
  }

  .cell-textarea {
    width: 100%;
    min-height: 40px;
    padding: 6px 8px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    resize: none;
    font-size: 14px;
    line-height: 1.5;
    box-sizing: border-box;
    outline: none;
    transition: border-color 0.2s;
  }

  .cell-textarea:focus {
    border-color: #409eff;
    box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
  }

  /* 表格行高自适应 */
  .el-table__row {
    height: auto !important;
  }

  /* 单元格顶部对齐，适配 textarea */
  .el-table__cell {
    display: flex;
    align-items: flex-start !important;
    padding: 4px 8px !important;
    height: auto !important;
    justify-content: space-between;
  }
</style>
